package com.laiketui.products.service;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.shaded.com.google.common.math.BigDecimalMath;
import com.google.zxing.common.detector.MathUtils;
import com.laiketui.common.api.*;
import com.laiketui.common.api.distribution.PubliceDistributionService;
import com.laiketui.common.api.plugin.PubliceBargainService;
import com.laiketui.common.api.plugin.seconds.PublicSecondsService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.ImgUploadUtils;
import com.laiketui.common.utils.tool.PriceUtils;
import com.laiketui.common.utils.tool.SensitiveWordTool;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.GoodsDataUtils;
import com.laiketui.common.utils.tool.jwt.JwtUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.orders.OrdersUtils;
import com.laiketui.core.utils.tool.*;
import com.laiketui.domain.Page;
import com.laiketui.domain.config.ConfiGureModel;
import com.laiketui.domain.config.ConfigModel;
import com.laiketui.domain.config.ProductConfigModel;
import com.laiketui.domain.distribution.DistributionGoodsModel;
import com.laiketui.domain.flashsale.FlashsaleActivityModel;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.mch.*;
import com.laiketui.domain.order.OrderDetailsModel;
import com.laiketui.domain.plugin.member.MemberProModel;
import com.laiketui.domain.presell.PreSellConfigModel;
import com.laiketui.domain.presell.PreSellGoodsModel;
import com.laiketui.domain.product.*;
import com.laiketui.domain.seckill.SecondsActivityModel;
import com.laiketui.domain.seckill.SecondsConfigModel;
import com.laiketui.domain.seckill.SecondsProModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.user.UserFootprintModel;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.ProductDetailsVo;
import com.laiketui.domain.vo.app.SearchGoodsVo;
import com.laiketui.domain.vo.cart.AddCartVo;
import com.laiketui.products.api.ProductService;
import com.laiketui.products.common.consts.AppConst;
import com.laiketui.root.annotation.DubboApiMethod;
import com.sun.javafx.collections.MappingChange;
import io.netty.util.internal.MathUtil;
import jdk.nashorn.internal.runtime.GlobalConstants;
import org.apache.commons.collections.MapUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 商品
 *
 * @author Trick
 * @date 2020/10/26 8:37
 */
@DubboService(version = "1.0.0")
public class ProductServiceImpl implements ProductService {
    private final Logger logger = LoggerFactory.getLogger(ProductServiceImpl.class);

    @Autowired
    private PublicUserService publicUserService;

    @Autowired
    private PublicMchService publicMchService;

    @Autowired
    private  FlashsaleRecordModelMapper flashsaleRecordModelMapper;

    @Autowired
    private ProductConfigModelMapper productConfigModelMapper;

    @Autowired
    private PublicMemberService publicMemberService;

    @DubboApiMethod(apiKey = "com.laike.app.listProduct",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public Map<String, Object> listProduct(SearchGoodsVo vo) {
        Map<String, Object> resultMap = new HashMap<>(16);
        List<Map<String, Object>> goodsList;
        int count = 0;
        String roleDiscount = "1";
        User user = null;
        String userId = "";
        //品牌id
        Integer brandId = null;
        BrandClassModel brandClassModel = null;
        try {
            //计算身份折扣
            if (!StringUtils.isEmpty(vo.getAccessId())) {
                user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil);
                if (user != null) {
                    userId = user.getUser_id();
                    if(user.getRole_id() != null){
                        //获取角色折扣
                        roleDiscount = publicMemberService.getMemberDiscountByUserId(user.getUser_id(),vo.getStoreId());
                    }
                }
            }
            //产品状态
            List<Integer> goodsStatus = new ArrayList<>();
            goodsStatus.add(DictionaryConst.GoodsStatus.NEW_GROUNDING);
            //不为主商城时,获取所属平台供应商
            int storeId = vo.getStoreId();
            List<MchModel> mchModels = null;
            if(storeId != GloabConst.StoreId.LUOCKOO_SHOP){
                MchModel mchModel = new MchModel();
                mchModel.setBelongStore(storeId);
                mchModel.setRecovery(GloabConst.RecycleType.NOT_RECYCLE);
                mchModels = mchModelMapper.select(mchModel);
                //重置商城id
                storeId = GloabConst.StoreId.LUOCKOO_SHOP;
            }
            List<Integer> mchIds = null;
            if(mchModels != null && mchModels.size() > 0){
                mchIds = mchModels.stream().map(MchModel::getId).collect(Collectors.toList());
            }
            //获取产品配置 是否显示下架产品
            ProductConfigModel productConfigModel = new ProductConfigModel();
            productConfigModel.setStore_id(storeId);
            productConfigModel = productConfigModelMapper.selectOne(productConfigModel);
            if (productConfigModel != null && productConfigModel.getIs_open() != 0) {
                goodsStatus.add(DictionaryConst.GoodsStatus.OFFLINE_GROUNDING);
            }
            Map<String, Object> parmaMap = new HashMap<>(16);
            //排序
            if (!StringUtils.isEmpty(vo.getSortCriteria())) {
                String field = "";
                switch (vo.getSortCriteria()) {
                    case "price":
                        field = "c.price";
//                        field = "min(c.price)";
                        break;
//                    case "comment_num":
//                        field = "a.comment_num";
//                        break;
//                    default:
//                        field = "a.volume";
                    default:
                        field = "rand()";
                }
                parmaMap.put("sortCriteria_sort", field);
                //排序类型
                String sort = "asc";
                if (!StringUtils.isEmpty(vo.getSort())) {
                    sort = vo.getSort();
                }
                parmaMap.put("sortCriteria_sort_type", sort);
            } else {
                //默认排序
                parmaMap.put("else_sort", DataUtils.Sort.DESC.toString());
            }
            //价格区间,品牌筛选
            if(StringUtil.isNotBlank(vo.getBrandId())){
                parmaMap.put("brand_id", vo.getBrandId());
                brandId = Integer.valueOf(vo.getBrandId());
                brandClassModel = new BrandClassModel();
                brandClassModel.setBrand_id(brandId);
                brandClassModel = brandClassModelMapper.selectOne(brandClassModel);
                if(!StringUtils.isEmpty(brandClassModel.getBrand_image())){
                    brandClassModel.setBrand_image(publicService.getImgPath(brandClassModel.getBrand_image(),vo.getStoreId()));
                }
            }
            if(StringUtil.isNotBlank(vo.getMinPrice())){
                parmaMap.put("min_price", vo.getMinPrice());
            }
            if(StringUtil.isNotBlank(vo.getMaxPrice())){
                parmaMap.put("max_price", vo.getMaxPrice());
            }
            if(StringUtil.isNotBlank(vo.getProductLabel())){
                parmaMap.put("s_type",vo.getProductLabel());
            }
            String keyword = "";
            //字符转义
            if(!StringUtils.isEmpty(vo.getKeyword())){
                keyword = URLDecoder.decode(vo.getKeyword(), GloabConst.Chartset.UTF8);
            }
            parmaMap.put("styleIds",vo.getStyleIds());
            parmaMap.put("cid", vo.getCid());
            parmaMap.put("store_id", storeId);
            parmaMap.put("GoodsStatus", goodsStatus);
            parmaMap.put("keyword", keyword);
            parmaMap.put("pageNo", vo.getPageNo());
            parmaMap.put("pageSize", vo.getPageSize());
            //指定平台供应商
            parmaMap.put("mchIds",mchIds);
            //只查询分类下的产品
//            parmaMap.put("show_adr",DictionaryConst.GoodsShowAdr.GOODSSHOWADR_CATEGORIES);
            if (productConfigModel != null && productConfigModel.getIs_display_sell_put() == 0) {
                //不展示已售罄的商品
                parmaMap.put("stockNum", "stockNum");
            }
            goodsList = productListModelMapper.getProductListDynamic(parmaMap);
            count = productListModelMapper.countProductListDynamic(parmaMap);
            for (Map<String, Object> map : goodsList) {
                //收藏id
                Integer collectionId = null;
                int pid = Integer.parseInt(map.get("id") + "");
                //获取用户收藏列表
                UserCollectionModel userCollectionModel = new UserCollectionModel();
                userCollectionModel.setStore_id(vo.getStoreId());
                userCollectionModel.setUser_id(userId);
                userCollectionModel.setP_id(pid);
                userCollectionModel = userCollectionModelMapper.selectOne(userCollectionModel);
                if (userCollectionModel != null) {
                    collectionId = userCollectionModel.getId();
                }
                int stockNum;
                //图片url
                String imgUrl = map.get("imgurl") + "";
                String coverMap = map.get("cover_map") + "";
//                String name = map.get("name") + "";
//                String color = map.get("color") + "";
                String price = map.get("price").toString().split("\\.")[0];
                String productTitle = map.get("product_title") + "";

//                BigDecimal vipYprice = new BigDecimal(price);
                String discountPrice = PriceUtils.mul2(price,roleDiscount);


                //获取图片
//                imgUrl = publicService.getImgPath(imgUrl, vo.getStoreId());
                //获取商品库存
                stockNum = confiGureModelMapper.countConfigGureNum(pid);
                //封面图
                coverMap = publicService.getImgPath(coverMap, vo.getStoreId());

                //商品分类名称
                String categoryName = "";
                //商品分类
                String goodsClass = MapUtils.getString(map,"product_class");
                String[] goodsClassList = goodsClass.trim().split("-");
                //获取分类名称
                ProductClassModel productClassModel = new ProductClassModel();
                productClassModel.setCid(Integer.parseInt(goodsClassList[goodsClassList.length-1]));
                productClassModel = productClassModelMapper.selectOne(productClassModel);
                if (productClassModel != null) {
                    categoryName = productClassModel.getPname();
                }
                //风格名称
                String styleName = MapUtils.getString(map,"style_name");
                map.put("categoryName",categoryName);
                map.put("styleName",styleName);
                map.put("name", productTitle);
                map.put("collectionId",collectionId);
//                map.put("size", productTitle);
                //售价
                map.put("price",price);
                map.put("discountPrice", discountPrice);
                map.put("coverImg",coverMap);
//                map.put("imgUrl", imgUrl);
                map.put("num", stockNum);
//                int payPeople = orderDetailsModelMapper.payPeople(vo.getStoreId(), pid);
//                map.put("payPeople", payPeople);
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("商品列表出现异常：", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SSXQWLYC, "商品列表网络异常", "hotSearch");
        }

        resultMap.put("goodsList", goodsList);
        resultMap.put("total", count);
        if(brandId != null){
            resultMap.put("brandInfo",brandClassModel);
            MchModel mchModel = new MchModel();
            mchModel.setId(brandClassModel.getMch_id());
            mchModel = mchModelMapper.selectOne(mchModel);
            resultMap.put("mchName",mchModel.getName());
        }
        return resultMap;
    }

    @DubboApiMethod(apiKey = "com.laike.app.listSimilarProduct",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public Map<String, Object> listSimilarProduct(Integer productId,Integer storeId,String token) {
        Map<String, Object> resultMap = new HashMap<>(16);
        List<Map<String, Object>> goodsList = new ArrayList<>();
        Map<String,Object> goodsMap = new HashMap<>();
        Map<String,Object> parmaMap = new HashMap<>();
        String roleDiscount = "1";
        User user = null;
        String userId = "";
        parmaMap.put("pid",productId);
        parmaMap.put("store_id",storeId);
        goodsList = productListModelMapper.getProductListDynamic(parmaMap);

        if(goodsList.size() > 0) {
            goodsMap = goodsList.get(0);
        }

        try{
            //计算身份折扣
            if (!StringUtils.isEmpty(token)) {
                user = RedisDataTool.getRedisUserCache(token, redisUtil);
                if (user != null) {
                    userId = user.getUser_id();
                    if(user.getRole_id() != null){
                        //获取角色折扣
                        roleDiscount = publicMemberService.getMemberDiscountByUserId(user.getUser_id(),storeId);
                    }
                }
            }
            if(MapUtils.isNotEmpty(goodsMap)){
                String price = goodsMap.get("price").toString();
                Map<String, Object> paramMap = new HashMap<>();

//                paramMap.put("min_price", minPrice);
//                paramMap.put("max_price", maxPrice);
                //同风格、同品类
                paramMap.put("cid",goodsMap.get("product_class").toString());
                paramMap.put("styleIds",goodsMap.get("style_id").toString());
                paramMap.put("store_id",storeId);
                paramMap.put("sortCriteria_sort", "c.price");
                paramMap.put("sortCriteria_sort_type","asc");
                goodsList = productListModelMapper.getProductListDynamic(paramMap);
                //同类推荐商品价格区间在0.85到1.15之间
                String maxPrice = PriceUtils.mul2(price, "1.15");
                String minPrice = PriceUtils.mul2(price, "0.85");
                goodsList = goodsList.stream()
                        .filter(goods -> Double.valueOf(minPrice) <= Double.valueOf(MapUtils.getString(goods,"price"))
                                && Double.valueOf(MapUtils.getString(goods,"price")) <= Double.valueOf(maxPrice))
                        .collect(Collectors.toList());
            }
            goodsList.removeIf(item -> productId.equals(MapUtils.getInteger(item,"id")));
            String finalRoleDiscount = roleDiscount;
            goodsList.forEach(map->{
                String imgurl = MapUtils.getString(map, "img");
                String imgPath = publicService.getImgPath(imgurl, storeId);
                String styleName = MapUtils.getString(map, "style_name");
                String price = map.get("price").toString().split("\\.")[0];
                //商品分类名称
                String categoryName = "";
                //商品分类
                String goodsClass = MapUtils.getString(map,"product_class");
                String[] goodsClassList = goodsClass.trim().split("-");
                //获取分类名称
                ProductClassModel productClassModel = new ProductClassModel();
                productClassModel.setCid(Integer.parseInt(goodsClassList[goodsClassList.length-1]));
                productClassModel = productClassModelMapper.selectOne(productClassModel);
                if (productClassModel != null) {
                    categoryName = productClassModel.getPname();
                }
                String discountPrice = PriceUtils.mul2(price, finalRoleDiscount);
                map.put("discountPrice",discountPrice);
                map.put("categoryName",categoryName);
                map.put("goodsImg",imgPath);
                map.put("styleName",styleName);
            });
        }catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("商品列表出现异常：", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SSXQWLYC, "商品列表网络异常", "hotSearch");
        }
        resultMap.put("goodsList",goodsList);
        return resultMap;
    }


    @DubboApiMethod(apiKey = "com.laike.products.getcomment",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public Map<String, Object> getcomment(int storeId, String language, String accessId, int goodsId, String isbargain, int type, int pageNo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new Hashtable<>(16);
        //评论数量
        int commentsTotal = 0;
        //好评数量
        int commentsHao = 0;
        //中评数量
        int commentsZhong = 0;
        //差评数量
        int commentsCha = 0;
        //评论图片数量
        int commentsImage = 0;
        try {
            Page pageModel = Page.newBuilder((pageNo - 1) * GloabConst.PageEnum.TERMINAL_DEFAULT_PAGESIZE, GloabConst.PageEnum.TERMINAL_DEFAULT_PAGESIZE, null);
            //根据条件获取评论信息
            Map<String, Object> parmaMap = new HashMap<>(16);
            parmaMap.put("store_id", storeId);
            parmaMap.put("pid", goodsId);
            parmaMap.put("pageNo", pageModel.getPageNo());
            parmaMap.put("pageSize", pageModel.getPageSize());
            parmaMap.put("group_commentId", "group_commentId");
            //类型(0=全部,1=好评,2=中评,3=差评,4=有图)
            parmaMap.put("type", type);
            List<Map<String, Object>> commentsMap = publicService.getGoodsCommentList(parmaMap);

            parmaMap.clear();
            parmaMap.put("store_id", storeId);
            parmaMap.put("pid", goodsId);
            commentsTotal = commentsModelMapper.countCommentsUserDynamicByPid(parmaMap);

            Map<String, Object> haoPinMap = new HashMap<>(16);
            haoPinMap.putAll(parmaMap);
            haoPinMap.put("type", 1);
            commentsHao = commentsModelMapper.countCommentsUserDynamicByPid(haoPinMap);

            Map<String, Object> zhongPinMap = new HashMap<>(16);
            zhongPinMap.putAll(parmaMap);
            zhongPinMap.put("type", 2);
            commentsZhong = commentsModelMapper.countCommentsUserDynamicByPid(zhongPinMap);

            Map<String, Object> chaPinMap = new HashMap<>(16);
            chaPinMap.putAll(parmaMap);
            chaPinMap.put("type", 3);
            commentsCha = commentsModelMapper.countCommentsUserDynamicByPid(chaPinMap);

            Map<String, Object> imageMap = new HashMap<>(16);
            imageMap.putAll(parmaMap);
            imageMap.put("type", 4);
            commentsImage = commentsModelMapper.countCommentsUserDynamicByPid(imageMap);

            resultMap.put("data", commentsMap);
            resultMap.put("comments_total", commentsTotal);
            resultMap.put("comments_hao", commentsHao);
            resultMap.put("comments_zhong", commentsZhong);
            resultMap.put("comments_cha", commentsCha);
            resultMap.put("comments_image", commentsImage);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("加载评论异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getcomment");
        }
        return resultMap;
    }


    @DubboApiMethod(apiKey = "com.laike.products.immediately_cart",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public boolean immediatelyCart(int storeId, String language, String accessId, String productJson, String orderType) throws LaiKeAPIException {
        boolean result = false;
        List<Map<String, Object>> productList = null;
        try {
            try {
                productList = JSON.parseObject(productJson, new TypeReference<List<Map<String, Object>>>() {
                });
            } catch (JSONException j) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSGSBZQ, productJson + ">参数格式不正确", "immediatelyCart");
            }
            Map<String, Object> productMap = null;
            if (StringUtils.isEmpty(orderType)) {
                orderType = DictionaryConst.OrdersType.ORDERS_HEADER_GM;
            }
            List<Map<String, Object>> ret = publicService.productsList(productList, "", 0, orderType);
            if (!CollectionUtils.isEmpty(ret)) {
                //商品详情页的立即购买按钮 最多只有一条数据
                productMap = ret.get(0);
            }
            if (productMap != null && productMap.size() > 0) {
                result = true;
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("立即购买异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "immediatelyCart");
        }
        return result;
    }

    @DubboApiMethod(apiKey = "com.laike.products.order_number",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public String builderOrderNo() throws LaiKeAPIException {
        String orderNo = "";
        try {
            orderNo = OrdersUtils.builderOrderNo();
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成订单异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "builderOrderNo");
        }
        return orderNo;
    }

    @DubboApiMethod(apiKey = "com.laike.products.comment",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public Map<String, Object> getOrderDetailInfo(int storeId, String language, String accessId, int orderDetailsId) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        List<Map<String, Object>> goodsDetailInfoList = new ArrayList<>();
        try {
            if (!StringUtils.isEmpty(accessId)) {
                Object userObj = redisUtil.get(GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN + accessId);
                if (userObj != null) {
                    List<Integer> orderStatusList = new ArrayList<>();
                    orderStatusList.add(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_COMPLETE);
                    Map<String, Object> parmaMap = new HashMap<>(16);
                    parmaMap.put("store_id", storeId);
                    parmaMap.put("oderDetailId", orderDetailsId);
                    parmaMap.put("r_statusList", orderStatusList);
                    //获取订单详情明细信息
                    goodsDetailInfoList = orderDetailsModelMapper.getOrderDetailByGoodsInfo(parmaMap);
                    for (Map<String, Object> map : goodsDetailInfoList) {
                        String productTitle = map.get("product_title") + "";
                        String imgUrl = map.get("img") + "";
                        imgUrl = publicService.getImgPath(imgUrl, storeId);

                        map.put("product_title", productTitle);
                        map.put("commodityIcon", imgUrl);
                    }
                } else {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QDL, "请登录", "getOrderDetailInfo");
                }
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_CSCW, "参数错误", "getOrderDetailInfo");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取订单商品数据异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getOrderDetailInfo");
        }
        resultMap.put("commentList", goodsDetailInfoList);
        return resultMap;
    }


    @DubboApiMethod(apiKey = "com.laike.products.base64_image_content",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public boolean base64ImageContent(String base64Str, String path) throws LaiKeAPIException {
        try {
            ImageBase64ConverterUtils.convertBase64ToFile(base64Str, path);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("base64图片上传异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "base64ImageContent");
        }
        return true;
    }

    @DubboApiMethod(apiKey = "com.laike.products.add_comment",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> addComment(MainVo vo, int anonymous, int orderDetailsId,
                                          Integer start, String comment, Integer imgIndex, Integer imgNum, MultipartFile image) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            if (com.laiketui.core.diyJavaFunction.StringUtils.isEmpty(comment)) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PLNRBNWK, "评论内容不能为空", "addComment");
            }
            //是否追评标识
            boolean isReview = false;
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
            //获取订单明细信息
            OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
            orderDetailsModel.setId(orderDetailsId);
            orderDetailsModel = orderDetailsModelMapper.selectOne(orderDetailsModel);
            if (orderDetailsModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WZDGDDXX, "未找到该订单信息", "addComment");
            }
            if (!user.getUser_id().equals(orderDetailsModel.getUser_id())) {
                logger.warn("用户 user = " + user.getUser_id() + " 正在请求订单id=" + orderDetailsId + ";被拦截!");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_FFSJ, "非法数据", "addComment");
            }
            if (start == null || start == 0) {
                isReview = true;
            }
            if (!isReview) {
                if (start < 1 || start > 5) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_PXCGFW, "评星超过范围");
                }
            }
            String orderNo = orderDetailsModel.getR_sNo();
            //获取商品规格信息
            ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(orderDetailsModel.getSid());
            if (confiGureModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPGGSJCW, "商品规格数据错误");
            }

            //检查是否已经评论过了
            CommentsModel commentsModel = new CommentsModel();
            commentsModel.setOid(orderNo);
            commentsModel.setOrder_detail_id(orderDetailsId);
            commentsModel = commentsModelMapper.selectOne(commentsModel);
            if (!isReview) {
                if (commentsModel != null) {
                    logger.warn("用户 user = " + user.getUser_id() + " 正在重复评论,订单号=" + orderNo + ";被拦截!");
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YPLGL, "已评论过了");
                }
            } else {
                if (commentsModel == null) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXPLHZP, "请先评论后追评");
                }
                logger.debug(user.getUser_id() + " 开始追加评论");
            }

            logger.debug(user.getUser_id() + "的评论,原内容:" + comment);
            //评论脱敏处理
            comment = sensitiveWordTool.filterInfo(comment);
            //评论xss防范
            comment = XssUtil.stripXSS(comment);
            logger.debug(user.getUser_id() + "的评论,处理后的内容:" + comment);

            int count;
            CommentsModel commentsSave = new CommentsModel();
            if (isReview) {
                if (imgNum != null) {
                    //上传图片 只有到最后一张图片才会真正保存到数据库中
                    imgComment(vo, commentsModel.getId(), image, imgIndex, imgNum, 1);
                }
                if (imgNum == null || (imgIndex + 1) == imgNum) {
                    //追加评论
                    commentsSave.setId(commentsModel.getId());
                    commentsSave.setReview(comment);
                    commentsSave.setReview_time(new Date());
                    count = commentsModelMapper.updateByPrimaryKeySelective(commentsSave);
                } else {
                    count = 1;
                }
            } else {
                //添加评论
                commentsSave.setStore_id(vo.getStoreId());
                commentsSave.setOid(orderNo);
                commentsSave.setUid(user.getUser_id());
                commentsSave.setPid(confiGureModel.getPid() + "");
                commentsSave.setAttribute_id(confiGureModel.getId());
                commentsSave.setContent(comment);
                commentsSave.setCommentType(start + "");
                commentsSave.setAnonymous(anonymous + "");
                commentsSave.setOrder_detail_id(orderDetailsId);
                commentsSave.setAdd_time(new Date());
                count = commentsModelMapper.insertSelective(commentsSave);
            }

            if (count > 0) {
                if (!isReview) {
                    //增加商品评论的数量
                    count = productListModelMapper.updateAddCommentNum(confiGureModel.getPid());
                }
                if (count < 1) {
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_FFRQ, "非法入侵");
                }
                resultMap.put("cid", commentsSave.getId());
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_FFRQ, "非法入侵");
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("商品评论异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "addComment");
        }
        return resultMap;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> imgComment(MainVo vo, int cid, MultipartFile file, int imgIndex, int imgNum, Integer type) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil);
            if (user != null) {
                if (type == null) {
                    type = 0;
                }
                String key = user.getUser_id() + cid;
                //商品图片集
                List<String> imgUlrs = new ArrayList<>();
                if (file != null) {
                    if (imgIndex == 0) {
                        //清空缓存
                        redisUtil.del(GloabConst.RedisHeaderKey.COMMENTS_UPLOAD_KEY + key);
                    }
                    //获取之前的图片
                    Object obj = redisUtil.get(GloabConst.RedisHeaderKey.COMMENTS_UPLOAD_KEY + key);
                    if (obj != null) {
                        imgUlrs = DataUtils.cast(obj);
                        if (imgUlrs == null) {
                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLFMQSHZS, "网络繁忙,请稍后再试");
                        }
                    }
                    List<MultipartFile> files = new ArrayList<>();
                    files.add(file);
                    //默认使用oos
                    String uploadType = GloabConst.UploadConfigConst.IMG_UPLOAD_OSS;
                    //获取店铺信息
                    ConfigModel configModel = new ConfigModel();
                    configModel.setStore_id(vo.getStoreId());
                    configModel = configModelMapper.selectOne(configModel);
                    if (configModel != null) {
                        uploadType = configModel.getUpserver();
                    }
                    //图片上传
                    List<String> urls = publiceService.uploadImage(files, uploadType, vo.getStoreType(), vo.getStoreId());
                    if (urls.size() != files.size()) {
                        logger.info(String.format("图片上传失败 需上传:%s 实际上传:%s", files.size(), imgUlrs.size()));
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPSCSB, "图片上传失败", "returnData");
                    }
                    imgUlrs.add(ImgUploadUtils.getUrlImgByName(urls.get(0), true));
                    redisUtil.set(GloabConst.RedisHeaderKey.COMMENTS_UPLOAD_KEY + key, imgUlrs, 30);
                    if (imgNum != imgIndex + 1) {
                        resultMap.put("comment_id", cid);
                        return resultMap;
                    }
                }
                //清空缓存
                redisUtil.del(GloabConst.RedisHeaderKey.RETURN_UPLOAD_KEY + key);

                //记录图片
                for (String url : imgUlrs) {
                    CommentsImgModel commentsImgModel = new CommentsImgModel();
                    commentsImgModel.setComments_url(ImgUploadUtils.getUrlImgByName(url, true));
                    commentsImgModel.setComments_id(cid);
                    commentsImgModel.setType(type);
                    commentsImgModel.setAdd_time(new Date());
                    int count = commentsImgModelMapper.insertSelective(commentsImgModel);
                    if (count < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_TPSCSB, "图片上传失败");
                    }
                }
                return resultMap;
            }
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QZXDL, "请重新登录");
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("评论图片上传 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "imgComment");
        }
    }

    @Autowired
    private UserAddressMapper userAddressMapper;


    @DubboApiMethod(apiKey = "com.laike.products.productDetails",
            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
    @Override
    public Map<String, Object> details(ProductDetailsVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            //商品类型跟订单类型类似
//            String proType = vo.getType();
            Map<String, Object> parmaMap = new HashMap<>(16);
            User user = null;
            String token = vo.getAccessId();

            StringBuilder userId = new StringBuilder("游客").append(DateUtil.timeStamp());
            //商品分类名称
            String categoryName = "";
            //商品折扣价格
            String discountPrice;
            //折扣
            String roleDiscount = "1";
            //计算身份折扣
            roleDiscount = publicMemberService.getMemberDiscountByToken(token,vo.getStoreId());
            //是否收藏 0 = 未收藏
            int type = 0;
            //收藏id
            Integer collectionId = null;
            //商品信息
            Map<String, Object> goodsMap = new HashMap<>(16);
            //商品图片集
            List<String> imgList = new ArrayList<>();
            if (!StringUtils.isEmpty(token)) {
                Object userObj = redisUtil.get(GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN + vo.getAccessId());
                if (userObj != null) {
                    user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
                    if (user.getId() != null) {
                        user = userBaseMapper.selectByPrimaryKey(user.getId());
                    }
                    userId = new StringBuilder(user.getUser_id());
                    //获取用户收藏列表
                    UserCollectionModel userCollectionModel = new UserCollectionModel();
                    userCollectionModel.setStore_id(vo.getStoreId());
                    userCollectionModel.setUser_id(user.getUser_id());
                    userCollectionModel.setP_id(vo.getProductId());
                    userCollectionModel = userCollectionModelMapper.selectOne(userCollectionModel);
                    if (userCollectionModel != null) {
                        type = 1;
                        collectionId = userCollectionModel.getId();
                    }
                    //插入一条足迹记录
                    UserFootprintModel userFootprintModel = new UserFootprintModel();
                    userFootprintModel.setStore_id(vo.getStoreId());
                    userFootprintModel.setUser_id(user.getUser_id());
                    userFootprintModel.setP_id(vo.getProductId());
                    userFootprintModel.setAdd_time(new Date());
                    int fid = userFootprintModelMapper.saveUserFootprint(userFootprintModel);
                    if (fid < 1) {
                        logger.info(user.getUser_id() + " 用户足迹插入失败 商品id= " + vo.getProductId());
                    }
                }
            } else {
                //没有token则获取一个token返回出去
                token = JwtUtils.getToken(publicUserService.getUserLoginLife(vo.getStoreId()));
            }
            //获取产品数据
            ProductListModel productListModel = new ProductListModel();
            productListModel.setId(vo.getProductId());
            productListModel = productListModelMapper.selectOne(productListModel);
            if (productListModel != null) {
                //商品id
                int goodsId = productListModel.getId();
                //店铺id
                Integer mchId = productListModel.getMch_id();
                //商品状态
                String status = productListModel.getStatus();
                //商品标题
                String productTitle = productListModel.getProduct_title();
                //风格名称
                String styleName = productListModel.getStyleName();
                //商品一般属性
                String parameters = productListModel.getParameters();
                //实拍图
                String realPhotos = productListModel.getRealPhotos();
                String[] realPhotosArr = new String[]{};
                if(StringUtil.isNotBlank(realPhotos)){
                    realPhotosArr = realPhotos.split(",");
                }
                String defaultImg = productListModel.getDefaultImg();//商品详情新增加默认图数据
                String[] defaultImgArr = new String[]{};
                if(StringUtil.isNotBlank(defaultImg)){
                    boolean startWithComma = defaultImg.startsWith(",");
                    if(startWithComma){//防止数据错误
                        defaultImg = defaultImg.substring(1, defaultImg.length()-1);
                    }
                    defaultImgArr = defaultImg.split(",");
                }
                //获取商品标签
                String productLabel = productListModel.getS_type();

                //副标题
                String subTitle = productListModel.getSubtitle();
                //商品封面图
//                String imgUrl = productListModel.getImgurl();
                //商品分类
                String goodsClass = productListModel.getProduct_class();
                String[] goodsClassList = goodsClass.trim().split("-");
                //获取分类名称
                ProductClassModel productClassModel = new ProductClassModel();
                productClassModel.setCid(Integer.parseInt(goodsClassList[goodsClassList.length-1]));
                productClassModel = productClassModelMapper.selectOne(productClassModel);
                if (productClassModel != null) {
                    categoryName = productClassModel.getPname();
                }
                //商品详情内容
                String content = productListModel.getContent();
                //商品销量
                int volume = productListModel.getVolume();
                //商品真实销量
                Integer realVolume = productListModel.getReal_volume();
                //展示视频
                String video = publiceService.getImgPath(productListModel.getVideo(), vo.getStoreId());
                //展示视频缩略图
                String videoImg = "";
                if(!StringUtils.isEmpty(video)){
                        videoImg = video.concat("?x-oss-process=video/snapshot,t_5000,f_png,w_0,h_0,m_fast,ar_auto");
                }
                //添加一条商品浏览记录
                MchBrowseModel mchBrowseModel = new MchBrowseModel();
                mchBrowseModel.setStore_id(vo.getStoreId());
                mchBrowseModel.setToken(token);
                mchBrowseModel.setMch_id(mchId.toString());
                mchBrowseModel.setUser_id(userId.toString());
                mchBrowseModel.setEvent("访问了店铺");
                mchBrowseModel.setAdd_time(new Date());
                int id = mchBrowseModelMapper.saveBrowse(mchBrowseModel);
                if (id < 1) {
                    logger.info(userId + " 用户店铺浏览记录插入失败 店铺id= " + mchId);
                }
                //价格处理
                ProductListModel productListParma = new ProductListModel();
                productListParma.setId(productListModel.getId());
                productListParma.setStore_id(productListModel.getStore_id());
                //获取商品最低/最高价格
//                Map<String, BigDecimal> goodsPricMap = productListModelMapper.getGoodsPriceMinAndMax(productListParma);
//                BigDecimal minPrice = goodsPricMap.get("minPrice");
//                BigDecimal maxPrice = goodsPricMap.get("maxPrice");
//                BigDecimal minYprice = goodsPricMap.get("minYprice");
//                BigDecimal maxYprice = goodsPricMap.get("maxYprice");
//                //商品成本价
//                BigDecimal costprice = goodsPricMap.get("costprice");
                BigDecimal price = productListModelMapper.getFirstGoodsPrice(productListParma);
                //出售价格
                goodsMap.put("price", price);
//                if (user != null) {
//                    gradeRate = showGradeRate = BigDecimal.valueOf(publicMemberService.getMemberGradeRate(orderGoodsType, user.getUser_id(), vo.getStoreId()));
//                }
//                //未登录则用商城最低折扣来计算显示价
//                if (gradeRate.compareTo(new BigDecimal("1")) == 0) {
//                    showGradeRate = userGradeModelMapper.getGradeLow(vo.getStoreId()).divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
//                }
                discountPrice = PriceUtils.mul2(price.toString(),roleDiscount);
                goodsMap.put("discountPrice", discountPrice);
                //获取运费信息
                BigDecimal yunfei = publicGoodsService.getGoodsFreight(user, goodsId);
                //品牌处理
                String brandName = "无";
                Integer brandId = productListModel.getBrand_id();
                String mchName = "";
                if (brandId != null) {
                    BrandClassModel brandClassModel = new BrandClassModel();
                    brandClassModel.setBrand_id(brandId);
                    brandClassModel = brandClassModelMapper.selectOne(brandClassModel);
                    if (brandClassModel != null) {
                        brandName = brandClassModel.getBrand_name();
                    }
                    //显示工厂名称
                    MchModel mchModel = new MchModel();
                    mchModel.setId(mchId);
                    mchModel = mchModelMapper.selectOne(mchModel);
                    mchName = mchModel.getName();
                }
                //多规格的情况修正库存
                Map<Integer, Integer> otherStockNumMap = null;
                //其它活动规格id
                List<Integer> otherAttrIds = new ArrayList<>();
                //是否需要重新计算价格 比如 秒杀的百分比
                BigDecimal rePriceScale = null;
                //修订后的价格
                price = null;
                //修订后的规格价格
                Map<Integer, BigDecimal> priceReviseMap = new HashMap<>(16);
                //品牌在售商品数量
                ProductListModel productCount = new ProductListModel();
                productCount.setStatus(String.valueOf(DictionaryConst.GoodsStatus.NEW_GROUNDING));
                productCount.setBrand_id(brandId);
                int goodsCount = productListModelMapper.selectCount(productCount);
                //商品
                goodsMap.put("productId", goodsId);
                goodsMap.put("productName", productTitle);
                goodsMap.put("subTitle",subTitle);
                goodsMap.put("realPhotos",realPhotosArr);
                goodsMap.put("defaultImgArr",defaultImgArr);
                goodsMap.put("parameters",parameters);
                goodsMap.put("categoryName",categoryName);
                goodsMap.put("styleName",styleName);
                goodsMap.put("goodsCount",goodsCount);
                //商品标签
                goodsMap.put("productLabels",publicGoodsService.getGoodsLabelList(vo.getStoreId(),
                        DataUtils.convertToList(com.laiketui.common.utils.tool.str.StringUtils.trim(productLabel, SplitUtils.DH).split(SplitUtils.DH))));
//                goodsMap.put("vip_price", vipPrice);
//                goodsMap.put("photo_x", imgUrl);
                goodsMap.put("content", content);
//                goodsMap.put("img_arr", imgList);
                goodsMap.put("status", status);
                goodsMap.put("userId", userId);
                goodsMap.put("freight", yunfei.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
                goodsMap.put("freightName", yunfei.compareTo(new BigDecimal("0")) == 0 ? "免运费" : yunfei.setScale(2,BigDecimal.ROUND_HALF_DOWN).toString());
                goodsMap.put("brandName", brandName);
                goodsMap.put("brandId", brandId);
//                goodsMap.put("volume", volume + realVolume);
                goodsMap.put("productVideo", video);
                goodsMap.put("productVideoImg",videoImg);
                //获取弹出商品规格插件信息
//                ConfiGureModel confiGureModel = new ConfiGureModel();
//                confiGureModel.setPid(productListModel.getId());
//                confiGureModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS.toString());
//                confiGureModel.setStatus(DictionaryConst.ConfigureStatus.CONFIGURE_STATUS_OPEN);

                Example example = new Example(ConfiGureModel.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("pid",productListModel.getId())
                        .andEqualTo("recycle",DictionaryConst.ProductRecycle.NOT_STATUS.toString());
//                        .andEqualTo("status",DictionaryConst.ConfigureStatus.CONFIGURE_STATUS_OPEN);
//                example.setOrderByClause("price asc");
                //商品总库存
                int attrStockTotalNum = 0;
                //处理图片地址、库存
//                List<ConfiGureModel> confiGureModelList = confiGureModelMapper.select(confiGureModel);
                List<ConfiGureModel> confiGureModelList = confiGureModelMapper.selectByExample(example);
                for (int i = 0; i < confiGureModelList.size(); i++) {
                    ConfiGureModel confiGure = confiGureModelList.get(i);
                    attrStockTotalNum += confiGure.getNum();
                    //是否只显示选中的规格
                    if (otherAttrIds.size() > 0 && !otherAttrIds.contains(confiGure.getId())) {
                        confiGureModelList.remove(confiGure);
                        i--;
                        continue;
                    }
                    String goodsConfigureUrl = confiGure.getImg();
                    goodsConfigureUrl = publicService.getImgPath(goodsConfigureUrl, productListModel.getStore_id());
                    confiGure.setImg(goodsConfigureUrl);
                    //是否需要修正库存数量
                    if (otherStockNumMap != null) {
                        Integer currentStockNum = otherStockNumMap.get(confiGure.getId());
                        if (currentStockNum == null) {
                            currentStockNum = 0;
                        }
                        confiGure.setNum(currentStockNum);
                    }
                    if (priceReviseMap.size() < 1) {
                        //修正价格
                        if (price != null) {
                            if (rePriceScale != null) {
                                //百分比重新计算价格
                                confiGure.setPrice(confiGure.getPrice().multiply(rePriceScale).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP));
                            } else {
                                //固定值
                                confiGure.setPrice(price);
                            }
                        }
                    } else {
                        if (priceReviseMap.get(confiGure.getId()) != null) {
                            confiGure.setPrice(priceReviseMap.get(confiGure.getId()));
                        }

                    }
                    //限时折扣价格修改
//                    if (discount != null){
//                        confiGure.setPrice(confiGure.getPrice().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP));
//                    }
                }
                if (otherStockNumMap == null && !DictionaryConst.OrdersType.ORDERS_HEADER_IN.equals(vo.getType())) {
                    //普通商品
                    goodsMap.put("num", attrStockTotalNum);
                    logger.debug("当前商品总库存{},当前规格库存{}", productListModel.getNum(), attrStockTotalNum);
                    if (productListModel.getNum() != attrStockTotalNum) {
                        //修正库存
                        ProductListModel productListUpdate = new ProductListModel();
                        productListUpdate.setId(goodsId);
                        productListUpdate.setNum(attrStockTotalNum);
                        productListModelMapper.updateByPrimaryKeySelective(productListUpdate);
                        logger.debug("商品id:{}的总库存已经修正", goodsId);
                    }
                }
                //获取商品规格弹出窗口插件数据
                resultMap = GoodsDataUtils.getGoodsAttributeInfoV2(confiGureModelList, roleDiscount);
                resultMap.put("product", goodsMap);
                resultMap.put("mchName",mchName);
                resultMap.put("collectionId", collectionId);
//                resultMap.put("access_id", token);
                if (DictionaryConst.OrdersType.ORDERS_HEADER_KJ.equals(vo.getType())) {
                    resultMap.putAll(publiceBargainService.getBargainDataList(vo.getStoreId(), vo.getBargainId(), user));
                }
            } else {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在", "index");
            }
        } catch (LaiKeAPIException l) {
            logger.error("获取商品详情 错误", l);
            throw l;
        } catch (Exception e) {
            logger.error("获取商品详情异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPXXBWZ, "商品信息不完整", "index");
        }
        return resultMap;
    }
//    @DubboApiMethod(apiKey = "com.laike.products.productIndex",
//            login = false, module = AppConst.MODULE_NAME, version = "1.0.0")
//    @Override
//    public Map<String, Object> index(ProductDetailsVo vo) throws LaiKeAPIException {
//        Map<String, Object> resultMap = new HashMap<>(16);
//        try {
//            //商品类型跟订单类型类似
//            String proType = vo.getType();
//            Map<String, Object> parmaMap = new HashMap<>(16);
//            User user = null;
//            String token = vo.getAccessId();
//            StringBuilder userid = new StringBuilder("游客").append(DateUtil.timeStamp());
//
//            //商品折扣价格
//            BigDecimal vipPrice;
//            //折扣
//            BigDecimal gradeRate = new BigDecimal("1");
//            //商品规格
//            String unit = "";
//
//            //是否是会员
//            int isVip = 0;
//            //是否收藏 0 = 未收藏
//            int type = 0;
//            //收藏id
//            Integer collectionId = null;
//            //店铺图标
//            String logo = "";
//            //商品信息
//            Map<String, Object> goodsMap = new HashMap<>(16);
//            //预售商品信息
//            Map<String, Object> sellGoodMap = new HashMap<>(16);
//            //店铺信息
//            Map<String, Object> shopMap;
//            //评论信息
//            List<Map<String, Object>> commentsList;
//            // 总评论数目
//            int commentsTotal;
//            //商品图片集
//            List<String> imgList = new ArrayList<>();
//            //分类名称
//            String pname = "";
//            //产品活动类型
//            String active = "";
//            //优惠卷状态
//            int couponStatus = 0;
//            //限时折扣折扣值
//            BigDecimal discount = null;
//            if (!StringUtils.isEmpty(token)) {
//                Object userObj = redisUtil.get(GloabConst.RedisHeaderKey.LOGIN_ACCESS_TOKEN + vo.getAccessId());
//                if (userObj != null) {
//                    user = RedisDataTool.getRedisUserCache(vo.getAccessId(), redisUtil, true);
//                    if (user.getId() != null) {
//                        user = userBaseMapper.selectByPrimaryKey(user.getId());
//                    }
//                    userid = new StringBuilder(user.getUser_id());
//                    if (user.getGrade() != null) {
//                        isVip = user.getGrade() > 0 ? 1 : 0;
//                    }
//                    //获取用户收藏列表
//                    UserCollectionModel userCollectionModel = new UserCollectionModel();
//                    userCollectionModel.setStore_id(vo.getStoreId());
//                    userCollectionModel.setUser_id(user.getUser_id());
//                    userCollectionModel.setP_id(vo.getProductId());
//                    userCollectionModel = userCollectionModelMapper.selectOne(userCollectionModel);
//                    if (userCollectionModel != null) {
//                        type = 1;
//                        collectionId = userCollectionModel.getId();
//                    }
//                    //插入一条足迹记录
//                    UserFootprintModel userFootprintModel = new UserFootprintModel();
//                    userFootprintModel.setStore_id(vo.getStoreId());
//                    userFootprintModel.setUser_id(user.getUser_id());
//                    userFootprintModel.setP_id(vo.getProductId());
//                    userFootprintModel.setAdd_time(new Date());
//                    int fid = userFootprintModelMapper.saveUserFootprint(userFootprintModel);
//                    if (fid < 1) {
//                        logger.info(user.getUser_id() + " 用户足迹插入失败 商品id= " + vo.getProductId());
//                    }
//                }
//            } else {
//                //没有token则获取一个token返回出去
//                token = JwtUtils.getToken(publicUserService.getUserLoginLife(vo.getStoreId()));
//            }
//            //获取产品数据
//            ProductListModel productListModel = new ProductListModel();
//            productListModel.setId(vo.getProductId());
//            productListModel = productListModelMapper.selectOne(productListModel);
//            if (productListModel != null) {
//                //商品id
//                int goodsId = productListModel.getId();
//                //商品订单类型
//                String orderGoodsType = vo.getType();
//                //店铺id
//                Integer mchId = productListModel.getMch_id();
//                //商品状态
//                String status = productListModel.getStatus();
//                //商品标题
//                String productTitle = productListModel.getProduct_title();
//                //产品活动类型
//                active = productListModel.getActive();
//                //商品封面图
//                String imgUrl = productListModel.getImgurl();
//                //商品类别
//                String goodsClass = productListModel.getProduct_class();
//                //商品详情内容
//                String content = productListModel.getContent();
//                //商品销量
//                int volume = productListModel.getVolume();
//                //商品真实销量
//                Integer realVolume = productListModel.getReal_volume();
//                //展示视频
//                String video = productListModel.getVideo();
//                //商品视频
//                String proVideo = productListModel.getProVideo();
//
//
//                //是否能购买
//                int canbuy = 1;
//
//                imgUrl = publicService.getImgPath(imgUrl, vo.getStoreId());
//                //获取商品统计信息
//                shopMap = publicService.commodityInformation(vo.getStoreId(), mchId);
//                //获取店铺信息
//                MchModel mchModel = new MchModel();
//                mchModel.setStore_id(vo.getStoreId());
//                mchModel.setId(mchId);
//                mchModel = mchModelMapper.selectOne(mchModel);
//                if (mchModel != null) {
//                    shopMap.put("shop_id", mchId);
//                    shopMap.put("shop_name", mchModel.getName());
//                    //未营业
//                    if (mchModel.getIs_open().equals("0") || mchModel.getIs_open().equals("2")) {
//                        shopMap.put("is_open", mchModel.getIs_open());
//                    } else if (mchModel.getIs_open().equals("1")) {
//                        //营业时间判断是否营业
//                        String[] businessHours = mchModel.getBusiness_hours().split(SplitUtils.BL);
//                        //开始时间
//                        Date startTime = com.laiketui.common.utils.tool.DateUtil.dateFormateToDate(businessHours[0], GloabConst.TimePattern.HM);
//                        //结束时间
//                        Date endTime = com.laiketui.common.utils.tool.DateUtil.dateFormateToDate(businessHours[1], GloabConst.TimePattern.HM);
//                        //当前时间
//                        Date currentDate = com.laiketui.common.utils.tool.DateUtil.dateFormateToDate(new Date(), GloabConst.TimePattern.HM);
//                        //开始时间大于结束时间(跨天：例如 19：00~04：00 则当前时间 >= 19:00 || 当前时间 <= 04:00 -> 营业 )
//                        if (com.laiketui.common.utils.tool.DateUtil.dateCompare(startTime, endTime)) {
//                            if (!com.laiketui.common.utils.tool.DateUtil.dateCompare(startTime, currentDate)
//                                    || !com.laiketui.common.utils.tool.DateUtil.dateCompare(currentDate, endTime)) {
//                                //营业
//                                shopMap.put("is_open", "1");
//                            } else {
//                                //未营业
//                                shopMap.put("is_open", "2");
//                            }
//                        } else {//开始时间小于结束时间（当天）则当前时间 >= 19:00 && 当前时间 <= 04:00 -> 营业
//                            if (!com.laiketui.common.utils.tool.DateUtil.dateCompare(startTime, currentDate)
//                                    && !com.laiketui.common.utils.tool.DateUtil.dateCompare(currentDate, endTime)) {
//                                //营业
//                                shopMap.put("is_open", "1");
//                            } else {
//                                //未营业
//                                shopMap.put("is_open", "2");
//                            }
//                        }
//                    } else {
//                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "店铺未设置营业状态");
//                    }
//                    String logoUrl = publicService.getImgPath(mchModel.getLogo(), vo.getStoreId());
//                    shopMap.put("shop_logo", logoUrl);
//                    String headImg = publicService.getImgPath(mchModel.getHead_img(), vo.getStoreId());
//                    shopMap.put("shop_head", headImg);
//                    shopMap.put("is_lock", mchModel.getIs_lock());
//                }
//                //添加一条商品浏览记录
//                MchBrowseModel mchBrowseModel = new MchBrowseModel();
//                mchBrowseModel.setStore_id(vo.getStoreId());
//                mchBrowseModel.setToken(token);
//                mchBrowseModel.setMch_id(mchId.toString());
//                mchBrowseModel.setUser_id(userid.toString());
//                mchBrowseModel.setEvent("访问了店铺");
//                mchBrowseModel.setAdd_time(new Date());
//                int id = mchBrowseModelMapper.saveBrowse(mchBrowseModel);
//                if (id < 1) {
//                    logger.info(userid + " 用户店铺浏览记录插入失败 店铺id= " + mchId);
//                }
//                //展示视频
//                if (com.laiketui.common.utils.tool.str.StringUtils.isNotEmpty(video)) {
//                    imgList.add(publiceService.getImgPath(video, vo.getStoreId()));
//                }
//                //获取该商品图片集
//                ProductImgModel productImgModel = new ProductImgModel();
//                productImgModel.setProduct_id(vo.getProductId());
//                List<ProductImgModel> productImgList = productImgModelMapper.select(productImgModel);
//                for (ProductImgModel productImg : productImgList) {
//                    String goodsImgUrl = productImg.getProduct_url();
//                    goodsImgUrl = publicService.getImgPath(goodsImgUrl, vo.getStoreId());
//                    imgList.add(goodsImgUrl);
//                }
//                //产品类型处理
//                String[] goodsClassList = goodsClass.trim().split("-");
//                for (String cid : goodsClassList) {
//                    if (StringUtils.isEmpty(cid)) {
//                        continue;
//                    }
//                    //获取分类名称 如果一级没查到则网上查直到查到为止
//                    ProductClassModel productClassModel = new ProductClassModel();
//                    productClassModel.setCid(Integer.parseInt(cid));
//                    productClassModel = productClassModelMapper.selectOne(productClassModel);
//                    if (productClassModel != null) {
//                        pname = productClassModel.getPname();
//                        break;
//                    }
//                }
//                //产品内容xss拦截处理
//                //content = XssUtil.stripXSS(content);
//
//                //价格处理
//                ProductListModel productListParma = new ProductListModel();
//                productListParma.setId(productListModel.getId());
//                productListParma.setStore_id(productListModel.getStore_id());
//                //获取商品最低/最高价格
//                Map<String, BigDecimal> goodsPricMap = productListModelMapper.getGoodsPriceMinAndMax(productListParma);
//                BigDecimal minPrice = goodsPricMap.get("minPrice");
//                BigDecimal maxPrice = goodsPricMap.get("maxPrice");
//                BigDecimal minYprice = goodsPricMap.get("minYprice");
//                BigDecimal maxYprice = goodsPricMap.get("maxYprice");
//                //商品成本价
//                BigDecimal costprice = goodsPricMap.get("costprice");
//                //出售价格
//                goodsMap.put("price", minPrice);
//                //原来价格
//                goodsMap.put("yprice", minYprice);
//                goodsMap.put("vip_yprice", minPrice);
//                //计算折扣价
//                BigDecimal showGradeRate = new BigDecimal("1");
//                if (user != null) {
//                    gradeRate = showGradeRate = BigDecimal.valueOf(publicMemberService.getMemberGradeRate(orderGoodsType, user.getUser_id(), vo.getStoreId()));
//                }
//                //未登录则用商城最低折扣来计算显示价
//                if (gradeRate.compareTo(new BigDecimal("1")) == 0) {
//                    showGradeRate = userGradeModelMapper.getGradeLow(vo.getStoreId()).divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
//                }
//                vipPrice = minPrice.multiply(showGradeRate);
//                goodsMap.put("vip_price", vipPrice);
//                if (DictionaryConst.OrdersType.ORDERS_HEADER_FX.equals(proType)) {
//                    goodsMap.put("is_distribution", 1);
//                    goodsMap.put("vip_price", 0);
//                } else {
//                    goodsMap.put("is_distribution", 0);
//                }
//                //获取运费信息
//                BigDecimal yunfei = publicGoodsService.getGoodsFreight(user, goodsId);
//                //品牌处理
//                String brandName = "无";
//                Integer brandId = productListModel.getBrand_id();
//                if (brandId != null) {
//                    BrandClassModel brandClassModel = new BrandClassModel();
//                    brandClassModel.setBrand_id(brandId);
//                    brandClassModel = brandClassModelMapper.selectOne(brandClassModel);
//                    if (brandClassModel != null) {
//                        brandName = brandClassModel.getBrand_name();
//                    }
//                }
//                //多规格的情况修正库存
//                Map<Integer, Integer> otherStockNumMap = null;
//
//                //其它活动规格id
//                List<Integer> otherAttrIds = new ArrayList<>();
//                //是否需要重新计算价格 比如 秒杀的百分比
//                BigDecimal rePriceScale = null;
//                //修订后的价格
//                BigDecimal price = null;
//                //修订后的规格价格
//                Map<Integer, BigDecimal> priceReviseMap = new HashMap<>(16);
//                //修订后的积分商品兑换所需积分
//                Map<Integer, Integer> integralMap = null;
//                //如果是秒杀则获取秒杀价格、库存、秒杀状态
//                if (vo.getId() != null && DictionaryConst.OrdersType.ORDERS_HEADER_MS.equalsIgnoreCase(orderGoodsType)) {
//                    //秒杀详情不显示会员价
//                    gradeRate = new BigDecimal("1");
//                    //2021-10-21 14:36:41 新版秒杀
//                    //获取秒杀活动信息
//                    SecondsActivityModel secondsActivityModel = secondsActivityModelMapper.selectByPrimaryKey(vo.getId());
//                    if (secondsActivityModel == null) {
//                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_MSSPBCZ, "秒杀商品不存在");
//                    }
//
//                    //获取规格价格最小的价格,所有插件不应展示商品售价计算的价格,而应展示规格金额最低计算后的价格
//                    ConfiGureModel attrTemp = confiGureModelMapper.getProductMaxPriceAndMaxPrice(productListModel.getId());
//                    //秒杀商品售价
//                    BigDecimal goodsPrice = attrTemp.getPrice();
//
//                    //商品原价
//                    goodsMap.put("yprice", attrTemp.getYprice());
//                    //秒杀价格
//                    price = secondsActivityModel.getSeconds_price();
//                    if (secondsActivityModel.getPrice_type() == 0) {
//                        //如果设置的是百分比则每个规格的价格重新计算
//                        rePriceScale = price;
//                        price = goodsPrice.multiply(price).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP);
//                    }
//                    goodsMap.put("price", price);
//                    goodsMap.put("num", secondsActivityModel.getNum());
//                    goodsMap.put("max_num", secondsActivityModel.getMax_num());
//                    //获取秒杀限购 默认不限购
//                    int buyNum = 0;
//                    SecondsConfigModel secondsConfigModel = new SecondsConfigModel();
//                    secondsConfigModel.setStore_id(vo.getStoreId());
//                    secondsConfigModel.setMch_id(productListModel.getMch_id());
//                    secondsConfigModel = secondsConfigModelMapper.selectOne(secondsConfigModel);
//                    if (secondsConfigModel != null && secondsConfigModel.getBuy_num() > 0) {
//                        buyNum = secondsConfigModel.getBuy_num();
//                    }
//                    if (user != null && buyNum > 0) {
//                        //是否超过限购数量
//                        int secNum = secondsProModelMapper.getUserSecNum(secondsActivityModel.getId(), user.getUser_id());
//                        buyNum -= secNum;
//                        if (buyNum <= 0) {
//                            //超过限购数量
//                            buyNum = -1;
//                        }
//                    }
//                    goodsMap.put("buyNum", buyNum);
//                    //获取秒杀商品规格信息
//                    SecondsProModel secondsProModel = new SecondsProModel();
//                    secondsProModel.setStore_id(vo.getStoreId());
//                    secondsProModel.setActivity_id(secondsActivityModel.getId());
//                    secondsProModel.setIs_delete(DictionaryConst.ProductRecycle.NOT_STATUS);
//                    List<SecondsProModel> secondsProModelList = secondsProModelMapper.select(secondsProModel);
//                    //修正库存数量
//                    otherStockNumMap = new HashMap<>(16);
//                    for (SecondsProModel secondsPro : secondsProModelList) {
//                        otherStockNumMap.put(secondsPro.getAttr_id(), secondsPro.getNum());
//                    }
//
//                    //秒杀状态
//                    int secStatus = publicSecondsService.getSecondsStatus(vo.getStoreId(), secondsActivityModel.getId(), secondsActivityModel.getNum(), secondsActivityModel.getStarttime(), secondsActivityModel.getEndtime(), true);
//                    goodsMap.put("secStatus", secStatus);
//
//                    //倒计时
//                    long remainingTime = secondsActivityModel.getEndtime().getTime();
//                    //如果是预告则为开始时间
//                    if (SecondsProModel.SecondsStatus.SECKILL_STATUS_HERALD == secStatus) {
//                        remainingTime = secondsActivityModel.getStarttime().getTime();
//                    }
//                    goodsMap.put("remainingTime", remainingTime);
//                } else if (DictionaryConst.OrdersType.PTHD_ORDER_PM.equalsIgnoreCase(vo.getType())) {
//                } else if (DictionaryConst.OrdersType.ORDERS_HEADER_FX.equals(vo.getType())) {
//                    //获取分销商品集合otherAttrIds
//                    DistributionGoodsModel distributionGoodsModel = distributionGoodsModelMapper.selectByPrimaryKey(vo.getId());
//                    if (distributionGoodsModel == null) {
//                        throw new LaiKeAPIException(com.laiketui.domain.lktconst.ErrorCode.BizErrorCode.ERROR_CODE_FXSPBCZ, "分销商品不存在");
//                    }
//                    if (DictionaryConst.ProductRecycle.RECOVERY.equals(distributionGoodsModel.getRecycle())) {
//                        throw new LaiKeAPIException(com.laiketui.domain.lktconst.ErrorCode.BizErrorCode.ERROR_CODE_FXSPYBSC, "分销商品已被删除");
//                    }
//                    Map<String, Object> disUserInfo = null;
//                    if (user != null) {
//                        //获取用户分销商信息
//                        disUserInfo = userDistributionModelMapper.getUserGradeinfo(vo.getStoreId(), user.getUser_id());
//                    }
//                    //单位
//                    BigDecimal directMtype = BigDecimal.ZERO;
//                    //直推金额
//                    BigDecimal directM = BigDecimal.ZERO;
//                    //分销价格
//                    BigDecimal fxPrice;
//                    if (disUserInfo == null) {
//                        //不是分销身份则获取商城top1分销人
//                        DistributionGradeModel userTop1Distribution = distributionGradeModelMapper.getUserTop1Distribution(vo.getStoreId());
//                        if (userTop1Distribution == null) {
//                            logger.error("商城【{}】分销配置有问题：未配置分销等级!", vo.getStoreId());
//                            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QSZFXDJ, "请设置分销等级", "getGoodsList");
//                        }
//                        String gradeStr = userTop1Distribution.getSets();
//                        Map<String, Object> gradeMap = SerializePhpUtils.getDistributionGradeBySets(gradeStr);
//                        if (gradeMap.containsKey("direct_m_type")) {
//                            directMtype = new BigDecimal(gradeMap.get("direct_m_type").toString());
//                        }
//                        if (gradeMap.containsKey(DistributionGoodsModel.DistributionRuleKey.DIRECT_M)) {
//                            directM = new BigDecimal(gradeMap.get(DistributionGoodsModel.DistributionRuleKey.DIRECT_M).toString());
//                        }
//                    }else{
//                        Map<String, Object> gradeMap = SerializePhpUtils.getDistributionGradeBySets(MapUtils.getString(disUserInfo, "sets"));
//                        if (gradeMap.containsKey("direct_m_type")) {
//                            directMtype = new BigDecimal(gradeMap.get("direct_m_type").toString());
//                        }
//                        if (gradeMap.containsKey(DistributionGoodsModel.DistributionRuleKey.DIRECT_M)) {
//                            directM = new BigDecimal(gradeMap.get(DistributionGoodsModel.DistributionRuleKey.DIRECT_M).toString());
//                        }
//                    }
//                    //是否是自定义规则
//                    if (distributionGoodsModel.getDistribution_rule().equals(DistributionGoodsModel.DISTRIBUTION_RULE_CUSTOM)) {
//                        Map<String, String> setsMap = DataUtils.cast(SerializePhpUtils.getUnserializeObj(distributionGoodsModel.getRules_set(), Map.class));
//                        if (setsMap != null) {
//                            directMtype = new BigDecimal(String.valueOf(setsMap.get("direct_m_type")));
//                            directM = new BigDecimal(String.valueOf(setsMap.get(DistributionGoodsModel.DistributionRuleKey.DIRECT_M)));
//                        }
//                    }
//                    //计算分销商折扣价
//                    BigDecimal disPrice = BigDecimal.ZERO;
//                    if (user != null) {
//                        disPrice  = publiceDistributionService.getGoodsPrice(vo.getStoreId(), user.getUser_id(), minPrice);
//                    }else {
//                        disPrice = minPrice;
//                    }
//                    //最高可获取的金额
//                    if (directMtype.compareTo(BigDecimal.ONE) == 0) {
//                        //固定值
//                        fxPrice = directM;
//                    } else {
//                        //商品pv值
//                        BigDecimal pv = distributionGoodsModel.getPv();
//                        //获取分润基值
//                        BigDecimal profit = publiceDistributionService.getProfit(vo.getStoreId(), disPrice, costprice, null, BigDecimal.ONE, pv);
//                        logger.error("profit:" + profit);
//                        //百分比
//                        logger.error("directM:" + directM);
//                        fxPrice = profit.multiply(directM.multiply(new BigDecimal("0.01")));
//                    }
//                    if (BigDecimal.ZERO.compareTo(fxPrice) >= 0) {
//                        fxPrice = BigDecimal.ZERO;
//                    }
//                    goodsMap.put("directM",fxPrice.setScale(2,BigDecimal.ROUND_HALF_UP).toString());
//                    goodsMap.put("distributionPrice", directM);
//                    /*otherAttrIds.add(distributionGoodsModel.getS_id());
//                    ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(distributionGoodsModel.getS_id());
//                    if (confiGureModel == null) {
//                        throw new LaiKeAPIException(com.laiketui.domain.lktconst.ErrorCode.BizErrorCode.ERROR_CODE_SPGGSJCW, "商品规格数据错误");
//                    }
//                    vipPrice = confiGureModel.getPrice();
//                    //获取分销折扣
//                    if (user != null) {
//                        vipPrice = publiceDistributionService.getGoodsPrice(vo.getStoreId(), user.getUser_id(), vipPrice);
//                    }
//                    goodsMap.put("vip_yprice", price = vipPrice);*/
//                    //优化(31065):同一商品的不同规格需要在一个商品中进行展示。 获取所有规格（规格多组合的情况下，少一种组合前端报错？？？） 2022-09-07 17:51:49
//                    List<Integer> attrIdList = distributionGoodsModelMapper.selectDistributionGoodsAtrrIds(distributionGoodsModel.getP_id());
//                    for (Integer attrId : attrIdList) {
//                        otherAttrIds.add(attrId);
//                        ConfiGureModel confiGureModel = confiGureModelMapper.selectByPrimaryKey(attrId);
//                        if (confiGureModel == null) {
//                            throw new LaiKeAPIException(com.laiketui.domain.lktconst.ErrorCode.BizErrorCode.ERROR_CODE_SPGGSJCW, "商品规格数据错误");
//                        }
//                        vipPrice = confiGureModel.getPrice();
//                        //获取分销折扣
//                        if (user != null) {
//                            vipPrice = publiceDistributionService.getGoodsPrice(vo.getStoreId(), user.getUser_id(), vipPrice);
//                        }
//                        priceReviseMap.put(attrId, vipPrice);
//                        if (attrId.equals(distributionGoodsModel.getS_id())) {
//                            goodsMap.put("vip_yprice", price = vipPrice);
//                        }
//                    }
//                    //end
//                } else if (DictionaryConst.OrdersType.ORDERS_HEADER_IN.equals(vo.getType())) {
//                    //积分商品详情不显示会员价
//                    gradeRate = new BigDecimal("1");
//                    IntegralGoodsModel integralGoodsOld = integralGoodsModelMapper.selectByPrimaryKey(vo.getId());
//                    if (integralGoodsOld == null) {
//                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JFSPBCZ, "积分商品不存在");
//                    }
//                    //商品售价价格
//                    Map<String, Object> goodsInfo = DataUtils.cast(SerializePhpUtils.getUnserializeObj(productListModel.getInitial(), Map.class));
//                    BigDecimal goodsPrice = new BigDecimal(Objects.requireNonNull(MapUtils.getString(goodsInfo, "sj")));
//                    //商品原价
//                    goodsMap.put("yprice", goodsPrice);
//                    //积分商品价格
//                    price = integralGoodsOld.getMoney();
//                    goodsMap.put("price", price);
//                    goodsMap.put("integralNum", integralGoodsOld.getIntegral());
//                    //获取积分商品规格信息--已上架商品
//                    integralGoodsOld = new IntegralGoodsModel();
//                    integralGoodsOld.setStore_id(vo.getStoreId());
//                    integralGoodsOld.setGoods_id(vo.getProductId());
//                    integralGoodsOld.setIs_delete(0);
//                    integralGoodsOld.setStatus(DictionaryConst.GoodsStatus.NEW_GROUNDING);
//                    List<IntegralGoodsModel> allAttrIdGoods = integralGoodsModelMapper.select(integralGoodsOld);
//
//                    if (allAttrIdGoods == null || allAttrIdGoods.size() <= 0){
//                        //该商品无已上架规格--商品状态已下架
//                        status = DictionaryConst.GoodsStatus.OFFLINE_GROUNDING.toString();
//                    }else {
//                        //商品上架
//                        status = DictionaryConst.GoodsStatus.NEW_GROUNDING.toString();
//                        int num = 0;
//                        int maxNum = 0;
//                        //修正库存数量
//                        otherStockNumMap = new HashMap<>(16);
//                        //修正价格
//                        priceReviseMap = new HashMap<>();
//                        //不同规格兑换所需积分
//                        integralMap = new HashMap<>();
//                        for (IntegralGoodsModel integralGoodsModel : allAttrIdGoods) {
//                            otherStockNumMap.put(integralGoodsModel.getAttr_id(), integralGoodsModel.getNum());
//                            num += integralGoodsModel.getNum();
//                            maxNum += integralGoodsModel.getMax_num();
//                            priceReviseMap.put(integralGoodsModel.getAttr_id(), integralGoodsModel.getMoney());
//                            integralMap.put(integralGoodsModel.getAttr_id(), integralGoodsModel.getIntegral());
//
//                            //如果商品非所有规格已下架，将已下架的规格排除不显示
//                            otherAttrIds.add(integralGoodsModel.getAttr_id());
//
//                        }
//                        //库存
//                        goodsMap.put("num", num);
//                        goodsMap.put("max_num", maxNum);
//                    }
//                } else if (DictionaryConst.OrdersType.ORDERS_HEADER_FS.equals(vo.getType())){
//                    FlashsaleActivityModel flashsaleActivityModel = flashsaleActivityModelMapper.selectByPrimaryKey(vo.getId());
//                    if (flashsaleActivityModel == null) {
//                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ,"商品不存在");
//                    }
//                    //获取默认规格
//                    BigDecimal productDefaultPrice = confiGureModelMapper.getProductDefaultPrice(vo.getProductId());
//                    //截止时间秒级时间戳
//                    goodsMap.put("remainingTime", flashsaleActivityModel.getEndtime().getTime());
//                    //出售价格
//                    discount = flashsaleActivityModel.getDiscount().divide(new BigDecimal(10));
//                    goodsMap.put("price", productDefaultPrice
//                            .multiply(discount)
//                            .setScale(2,BigDecimal.ROUND_HALF_UP).toString());
//                    //原来价格
//                    goodsMap.put("yprice", productDefaultPrice.toString());
//                    Integer buylimit = flashsaleActivityModel.getBuylimit();
//                    //查询用户已购买数量
//                    if (user != null){
//                        Integer userPayNum = flashsaleRecordModelMapper.getUserPayNum(vo.getStoreId(), user.getUser_id(), vo.getId());
//                        if (userPayNum < buylimit){
//                            buylimit = buylimit - userPayNum;
//                        }else {
//                            buylimit = 0;
//                        }
//                    }
//                    //限购数量
//                    goodsMap.put("buyNum", buylimit);
//                }
//                //pro节点
//                goodsMap.put("pro_id", goodsId);
//                goodsMap.put("name", productTitle);
//                goodsMap.put("grade_rate", gradeRate);
//                goodsMap.put("vip_price", vipPrice);
//                goodsMap.put("unit", unit);
//                goodsMap.put("photo_x", imgUrl);
//                goodsMap.put("content", content);
//                goodsMap.put("cat_name", pname);
//                goodsMap.put("img_arr", imgList);
//                goodsMap.put("status", status);
//                goodsMap.put("user_id", userid);
//                goodsMap.put("freight", yunfei.setScale(2, BigDecimal.ROUND_HALF_DOWN).toString());
//                goodsMap.put("freight_name", yunfei.compareTo(new BigDecimal("0")) == 0 ? "免运费" : yunfei.setScale(2,BigDecimal.ROUND_HALF_DOWN).toString());
//                goodsMap.put("canbuy", canbuy);
//                goodsMap.put("brand_name", brandName);
//                goodsMap.put("volume", volume + realVolume);
//                goodsMap.put("yunfei", yunfei.setScale(2,BigDecimal.ROUND_HALF_DOWN).toString());
//                goodsMap.put("coverImage", publiceService.getImgPath(productListModel.getCover_map(), vo.getStoreId()));
//                goodsMap.put("video", publiceService.getImgPath(video, vo.getStoreId()));
//                goodsMap.put("proVideo", publiceService.getImgPath(proVideo, vo.getStoreId()));
//                //获取评论 首页只获取最新的一条
//                parmaMap.clear();
//                Page pageModel = Page.newBuilder(0, 1, null);
//                parmaMap.put("store_id", vo.getStoreId());
//                parmaMap.put("pid", goodsId);
//                parmaMap.put("pageNo", pageModel.getPageNo());
//                parmaMap.put("pageSize", pageModel.getPageSize());
//                commentsList = publicService.getGoodsCommentList(parmaMap);
//
//                CommentsModel commentsModel = new CommentsModel();
//                commentsModel.setPid(goodsId + "");
//                commentsTotal = commentsModelMapper.selectCount(commentsModel);
//
//
//                //获取弹出商品规格插件信息
//                ConfiGureModel confiGureModel = new ConfiGureModel();
//                confiGureModel.setPid(productListModel.getId());
//                confiGureModel.setRecycle(DictionaryConst.ProductRecycle.NOT_STATUS.toString());
//                //商品总库存
//                int attrStockTotalNum = 0;
//                //处理图片地址、库存
//                List<ConfiGureModel> confiGureModelList = confiGureModelMapper.select(confiGureModel);
//                for (int i = 0; i < confiGureModelList.size(); i++) {
//                    ConfiGureModel confiGure = confiGureModelList.get(i);
//                    attrStockTotalNum += confiGure.getNum();
//                    //是否只显示选中的规格
//                    if (otherAttrIds.size() > 0 && !otherAttrIds.contains(confiGure.getId())) {
//                        confiGureModelList.remove(confiGure);
//                        i--;
//                        continue;
//                    }
//                    String goodsConfigureUrl = confiGure.getImg();
//                    goodsConfigureUrl = publicService.getImgPath(goodsConfigureUrl, productListModel.getStore_id());
//                    confiGure.setImg(goodsConfigureUrl);
//                    //是否需要修正库存数量
//                    if (otherStockNumMap != null) {
//                        Integer currentStockNum = otherStockNumMap.get(confiGure.getId());
//                        if (currentStockNum == null) {
//                            currentStockNum = 0;
//                        }
//                        confiGure.setNum(currentStockNum);
//                    }
//                    if (priceReviseMap.size() < 1) {
//                        //修正价格
//                        if (price != null) {
//                            if (rePriceScale != null) {
//                                //百分比重新计算价格
//                                confiGure.setPrice(confiGure.getPrice().multiply(rePriceScale).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_HALF_UP));
//                            } else {
//                                //固定值
//                                confiGure.setPrice(price);
//                            }
//                        }
//                    } else {
//                        if (priceReviseMap.get(confiGure.getId()) != null) {
//                            confiGure.setPrice(priceReviseMap.get(confiGure.getId()));
//                        }
//
//                    }
//                    if (DictionaryConst.OrdersType.ORDERS_HEADER_IN.equals(vo.getType()) && integralMap != null) {
//                        if (integralMap.get(confiGure.getId()) != null) {
//                            confiGure.setIntegralPriceNum(integralMap.get(confiGure.getId()));
//                        } else {
//                            confiGure.setIntegralPriceNum(0);
//                        }
//                    }
//                    //限时折扣价格修改
//                    if (discount != null){
//                        confiGure.setPrice(confiGure.getPrice().multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP));
//                    }
//                }
//                if (otherStockNumMap == null && !DictionaryConst.OrdersType.ORDERS_HEADER_IN.equals(vo.getType())) {
//                    //普通商品
//                    goodsMap.put("num", attrStockTotalNum);
//                    logger.debug("当前商品总库存{},当前规格库存{}", productListModel.getNum(), attrStockTotalNum);
//                    if (productListModel.getNum() != attrStockTotalNum) {
//                        //修正库存
//                        ProductListModel productListUpdate = new ProductListModel();
//                        productListUpdate.setId(goodsId);
//                        productListUpdate.setNum(attrStockTotalNum);
//                        productListModelMapper.updateByPrimaryKeySelective(productListUpdate);
//                        logger.debug("商品id:{}的总库存已经修正", goodsId);
//                    }
//                }
//                //获取商品规格弹出窗口插件数据
//                resultMap = GoodsDataUtils.getGoodsAttributeInfo(confiGureModelList, gradeRate);
//                //会员价(会员商品才会享有)
//                if (vo.getVipSource() == null) {
//                    vo.setVipSource(DictionaryConst.WhetherMaven.WHETHER_NO);
//                }
//                if (vo.getVipSource().equals(DictionaryConst.WhetherMaven.WHETHER_OK)) {
//                    MemberProModel memberProModel = new MemberProModel();
//                    memberProModel.setPro_id(goodsId);
//                    memberProModel.setRecovery(DictionaryConst.ProductRecycle.NOT_STATUS);
//                    memberProModel = memberProModelMapper.selectOne(memberProModel);
//                    if (!Objects.isNull(memberProModel) && memberProModel.getId() != null) {
//                        if (!Objects.isNull(user) && user.getGrade() != null && user.getGrade().equals(User.MEMBER)) {
//                            Map<String, Object> config = memberConfigMapper.getConfig(vo.getStoreId());
//                            if (MapUtils.getInteger(config, "id") != null) {
//                                String memberDiscount = MapUtils.getString(config, "member_discount");
//                                List<Map<String, Object>> mapList = (List<Map<String, Object>>) resultMap.get("attribute_list");
//                                mapList.stream().forEach(map -> {
//                                    String amount = MapUtils.getString(map, "Price");
//                                    BigDecimal multiply = new BigDecimal(amount).multiply(new BigDecimal(memberDiscount));
//                                    BigDecimal divide = multiply.divide(new BigDecimal(10), 2, BigDecimal.ROUND_HALF_UP);
//                                    map.put("Price", divide);
//                                });
//                            }
//                        }
//                    }
//                }
//                //优惠卷流程
//                couponStatus = publicCouponService.index(productListModel.getStore_id());
//                //商品价格小数点处理
//                String vip_price = new BigDecimal(MapUtils.getString(goodsMap, "vip_price")).setScale(2, BigDecimal.ROUND_DOWN).toString();
//                String vip_yprice = new BigDecimal(MapUtils.getString(goodsMap, "vip_yprice")).setScale(2, BigDecimal.ROUND_DOWN).toString();
//                goodsMap.put("vip_price", vip_price);
//                goodsMap.put("vip_yprice", vip_yprice);
//                resultMap.put("logo", logo);
//                resultMap.put("pro", goodsMap);
//                resultMap.put("shop_list", shopMap);
//                resultMap.put("cs_price", minPrice);
//                resultMap.put("collection_id", collectionId);
//                resultMap.put("comments", commentsList);
//                resultMap.put("commentsTotal", commentsTotal);
//                resultMap.put("type", type);
//                resultMap.put("access_id", token);
//                resultMap.put("login_status", user != null ? 1 : 0);
//                resultMap.put("active", active);
//                resultMap.put("is_grade", 0);
//                resultMap.put("coupon_status", couponStatus);
//                // 为null前端
//                resultMap.put("coupon_str", "");
//                //预售商品信息
//                PreSellGoodsModel preSellGoodsModel = new PreSellGoodsModel();
//                preSellGoodsModel.setProduct_id(vo.getProductId());
//                preSellGoodsModel = preSellGoodsMapper.selectOne(preSellGoodsModel);
//                if (!Objects.isNull(preSellGoodsModel)) {
//                    //预售配置信息
//                    PreSellConfigModel preSellConfigModel = new PreSellConfigModel();
//                    preSellConfigModel.setStore_id(vo.getStoreId());
//                    preSellConfigModel = preSellConfigModelMapper.selectOne(preSellConfigModel);
//                    sellGoodMap.put("depositDesc", preSellConfigModel.getDeposit_desc());
//                    sellGoodMap.put("balanceDesc", preSellConfigModel.getBalance_desc());
//                    sellGoodMap.put("sellType", preSellGoodsModel.getSell_type());
//                    if (preSellGoodsModel.getSell_type().equals(PreSellGoodsModel.DEPOSIT_PATTERN)) {
//                        sellGoodMap.put("depositType", preSellGoodsModel.getPay_type());
//                        sellGoodMap.put("deposit", preSellGoodsModel.getDeposit());
//                        sellGoodMap.put("depositStart", DateUtil.dateFormate(preSellGoodsModel.getDeposit_start_time(), GloabConst.TimePattern.YMDHMS));
//                        sellGoodMap.put("depositEnd", DateUtil.dateFormate(preSellGoodsModel.getDeposit_end_time(), GloabConst.TimePattern.YMDHMS));
//                        Calendar calendar = Calendar.getInstance();
//                        calendar.setTime(preSellGoodsModel.getBalance_pay_time());
//                        calendar.set(Calendar.HOUR_OF_DAY, 0);
//                        calendar.set(Calendar.MINUTE, 0);
//                        calendar.set(Calendar.SECOND, 0);
//                        Date start = calendar.getTime();
//                        calendar.add(Calendar.DAY_OF_MONTH, 1);
//                        calendar.add(Calendar.SECOND, -1);
//                        Date end = calendar.getTime();
//                        sellGoodMap.put("startTime", DateUtil.dateFormate(start, GloabConst.TimePattern.YMDHMS));
//                        sellGoodMap.put("endTime", DateUtil.dateFormate(end, GloabConst.TimePattern.YMDHMS));
//                        sellGoodMap.put("balance", minPrice.subtract(preSellGoodsModel.getDeposit()));
//                    } else {
//                        sellGoodMap.put("sellNum", preSellGoodsModel.getSell_num());
//                        sellGoodMap.put("surplusNum", preSellGoodsModel.getSurplus_num());
//                        sellGoodMap.put("endTime", DateUtil.dateFormate(preSellGoodsModel.getDeadline(), GloabConst.TimePattern.YMDHMS));
//                    }
//                    sellGoodMap.put("deliveryTime", preSellGoodsModel.getDelivery_time());
//                    resultMap.put("sellGoodInfo", sellGoodMap);
//                    //库存处理
//
//                }
//                if (DictionaryConst.OrdersType.ORDERS_HEADER_KJ.equals(vo.getType())) {
//                    resultMap.putAll(publiceBargainService.getBargainDataList(vo.getStoreId(), vo.getBargainId(), user));
//                }
//            } else {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPBCZ, "商品不存在", "index");
//            }
//        } catch (LaiKeAPIException l) {
//            logger.error("获取商品详情 错误", l);
//            throw l;
//        } catch (Exception e) {
//            logger.error("获取商品详情异常", e);
//            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SPXXBWZ, "商品信息不完整", "index");
//        }
//        return resultMap;
//    }


    @Autowired
    private ProductModelMapper productModelMapper;

    @Autowired
    private PubliceBargainService publiceBargainService;

    @Autowired
    private DistributionGoodsModelMapper distributionGoodsModelMapper;

    @Autowired
    PublicCouponService publicCouponService;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    BrandClassModelMapper brandClassModelMapper;

    @Autowired
    UserGradeModelMapper userGradeModelMapper;

    @Autowired
    private PublicGoodsService publicGoodsService;

    @Autowired
    DistributionGradeModelMapper distributionGradeModelMapper;

    @Autowired
    ProductClassModelMapper productClassModelMapper;

    @Autowired
    ProductImgModelMapper productImgModelMapper;

    @Autowired
    MchBrowseModelMapper mchBrowseModelMapper;

    @Autowired
    MchModelMapper mchModelMapper;

    @Autowired
    UserFootprintModelMapper userFootprintModelMapper;

    @Autowired
    UploadConfigModelMapper uploadConfigModelMapper;

    @Autowired
    UserCollectionModelMapper userCollectionModelMapper;

    @Autowired
    OrderDetailsModelMapper orderDetailsModelMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    SensitiveWordTool sensitiveWordTool;

    @Autowired
    PubliceService publicService;

    @Autowired
    ConfiGureModelMapper confiGureModelMapper;

    @Autowired
    ConfigModelMapper configModelMapper;

    @Autowired
    CartModelMapper cartModelMapper;

    @Autowired
    ProductListModelMapper productListModelMapper;

    @Autowired
    CommentsModelMapper commentsModelMapper;

    @Autowired
    CommentsImgModelMapper commentsImgModelMapper;

    @Autowired
    ReplyCommentsModelMapper replyCommentsModelMapper;

    @Autowired
    SecondsProModelMapper secondsProModelMapper;

    @Autowired
    private SecondsActivityModelMapper secondsActivityModelMapper;

    @Autowired
    PtSecondsProModelMapper ptsecondsProModelMapper;

    @Autowired
    private PublicSecondsService publicSecondsService;

    @Autowired
    private IntegralGoodsModelMapper integralGoodsModelMapper;

    @Autowired
    private SecondsConfigModelMapper secondsConfigModelMapper;

    @Autowired
    private PreSellGoodsMapper preSellGoodsMapper;

    @Autowired
    private PreSellConfigModelMapper preSellConfigModelMapper;

    @Autowired
    private PubliceDistributionService publiceDistributionService;

    @Autowired
    private MemberConfigMapper memberConfigMapper;

    @Autowired
    private MemberProModelMapper memberProModelMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private FlashsaleActivityModelMapper flashsaleActivityModelMapper;

    @Autowired
    private UserDistributionModelMapper userDistributionModelMapper;
}

